package com.cysion.study.ui

import android.app.Activity
import android.content.Intent
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.text.Editable
import android.text.TextUtils
import android.text.format.DateFormat
import android.view.View
import com.baidu.mapapi.map.*
import com.baidu.mapapi.model.LatLng
import com.baidu.mapapi.search.core.PoiInfo
import com.baidu.mapapi.search.core.SearchResult
import com.baidu.mapapi.search.geocode.*
import com.baidu.mapapi.search.poi.*
import com.cysion.other.color
import com.cysion.study.R
import com.cysion.study.adapter.PMapAdapter
import com.cysion.study.entity.AddressMapEntity
import com.cysion.study.helper.UserCache
import com.cysion.study.ktbox.Box
import com.cysion.study.ktbox.base.BaseActivity
import com.cysion.study.ktbox.base.ITEM_CLICK
import com.cysion.study.ktbox.utils.CLog
import com.cysion.study.ktbox.utils.darkTextTheme
import com.cysion.study.uibox.bar.TopBar
import com.cysion.study.widget.ShowToast
import com.xw.repo.XEditText
import kotlinx.android.synthetic.main.activity_clockin_map_p.*
import java.lang.Double


class PClockinMapActivity : BaseActivity(), BaiduMap.OnMapClickListener {
    override fun getLayoutId(): Int = R.layout.activity_clockin_map_p

    private var mSensorManager: SensorManager? = null
    private var mBaiduMap: BaiduMap? = null
    private var locData: MyLocationData? = null
    private var speed = ""

    private var searchType = -1//1为地理编码 地图点击 2 关键字检索
    override fun initView() {

        darkTextTheme(color(R.color.white))
        topbar.apply {
            setTitleBackColor(color(R.color.white))
            setTitle("授课地址")
            setOnTopBarClickListener { obj, pos ->
                if (pos == TopBar.Pos.LEFT) {
                    finish()
                }
            }
        }

        tv_city.text == UserCache.city
        val sysTime = System.currentTimeMillis()//获取系统时间
        val sysTimeStr = DateFormat.format("HH:mm:ss", sysTime)//时间显示格式
//        TimeThread().start() //启动显示时间线程
//        mSensorManager = getSystemService(SENSOR_SERVICE) as SensorManager// 获取传感器管理服务
        mBaiduMap = mapView.map
        // 开启定位图层
        mBaiduMap?.isMyLocationEnabled = true

        val ms = MapStatus.Builder().overlook(0f).zoom(18.0f).build()
        val u1 = MapStatusUpdateFactory.newMapStatus(ms)
        //        mBaiduMap.setMapStatus(u1);
        mBaiduMap?.animateMapStatus(u1)

        locData = MyLocationData.Builder().accuracy(UserCache.radius)
            // 此处设置开发者获取到的方向信息，顺时针0-360
            .direction(mCurrentDirection.toFloat())
            .latitude(java.lang.Double.parseDouble(UserCache.lat))
            .longitude(java.lang.Double.parseDouble(UserCache.lon)).build()
        mBaiduMap?.setMyLocationData(locData)
        marker?.isDraggable = true
        mBaiduMap?.isBuildingsEnabled = true//是否显示立体的建筑物
        val config =
            MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL, true, null)
        mBaiduMap?.setMyLocationConfiguration(config)
        var latLng = LatLng(Double.parseDouble(UserCache.lat), Double.parseDouble(UserCache.lon))
        latLngs=latLng
        val msu = MapStatusUpdateFactory.newLatLng(latLng)
        mBaiduMap?.animateMapStatus(msu)
        CLog.e("@@@@定位位置=" + UserCache.city)
        initRefreshLayout()
        initRecyclerView()
        mBaiduMap?.setOnMarkerClickListener(object : BaiduMap.OnMarkerClickListener {
            override fun onMarkerClick(marker: Marker?): Boolean {
                val ll = marker!!.position
                println("###marker位置=" + ll.latitude + "###=" + ll.longitude)
                return true
            }

        })

        //设置地图是否可以移动
        mBaiduMap?.uiSettings?.isScrollGesturesEnabled = true

        //搜索实例
        mPoiSearch = PoiSearch.newInstance();
        //设置检索监听器
        mPoiSearch?.setOnGetPoiSearchResultListener(listener)


        //创建地理编码实例
        geocoder = GeoCoder.newInstance()
        // 发起反地理编码请求(经纬度->地址信息)
        var reverseGeoCodeOption = ReverseGeoCodeOption()
        // 设置反地理编码位置坐标
        reverseGeoCodeOption.location(latLng)
        geocoder?.reverseGeoCode(reverseGeoCodeOption);

        //创建地理编码检索监听
        geocoder?.setOnGetGeoCodeResultListener(geoListener);
        //拿到经纬度之后，就可以反地理编码获取地址信息了
        initGeoCoder(latLng)
        //百度地图点击事件
        mBaiduMap?.setOnMapClickListener(this)


        //处理搜索地址业务
        et_address.setOnXTextChangeListener(textChangeListener)
        tv_search.setOnClickListener {
            mapView.visibility = View.VISIBLE
            tv_search.visibility = View.GONE
        }

    }

    private var page = 0
    private var keyword = ""

    var textChangeListener: XEditText.OnXTextChangeListener =
        object : XEditText.OnXTextChangeListener {
            override fun afterTextChanged(str: Editable?) {
                if (!TextUtils.isEmpty(str.toString())) {
                    println("####输入搜索=" + str.toString())
                    keyword = str.toString()
                    dataList.clear()
                    mAdapter.notifyDataSetChanged()
                    tv_search.visibility=View.VISIBLE
                    initSearch()
                } else {
                    tv_search.visibility=View.GONE
                    mapView.visibility = View.VISIBLE
                }
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        }

    private fun initGeoCoder(latLng: LatLng?) {
        searchType = 1
        //发起逆地理编码检索
        geocoder?.reverseGeoCode(ReverseGeoCodeOption().location(latLng))
        //设置GeoCodeOption，发起geoCode检索
        geocoder?.geocode(GeoCodeOption().city(UserCache.city).address(UserCache.cacheAddress))

    }


    private fun initSearch() {
        searchType = 2
        //searchInCity城市内检索  一般用于手动输入检索
        mPoiSearch?.searchInCity(
            PoiCitySearchOption()
                .city(tv_city.text.toString()) //必填
                .keyword(keyword) //必填
                .isReturnAddr(true)
                .pageNum(page)
        )
        //发起检索 city 和 address是必填项
//       geocoder?.geocode(GeoCodeOption().city(UserCache.city).address(UserCache.cacheAddress))
    }


    //编辑检索监听
    var geoListener: OnGetGeoCoderResultListener = object : OnGetGeoCoderResultListener {
        override fun onGetGeoCodeResult(geoCodeResult: GeoCodeResult?) {}

        override fun onGetReverseGeoCodeResult(geoCodeResult: ReverseGeoCodeResult?) {
            if (geoCodeResult?.location != null) {
                if (geoCodeResult.error !== SearchResult.ERRORNO.NO_ERROR) { //没有检索到结果
                    ShowToast("未找到结果")
                    multiView.showEmpty()
                } else {
                    dataList.clear()
                    val latitude: kotlin.Double = geoCodeResult.getLocation().latitude
                    val longitude: kotlin.Double = geoCodeResult.getLocation().longitude
                    //拿到变化地点后的附近地址
                    val poiInfos: MutableList<PoiInfo> = geoCodeResult.poiList
                    println("###获取地理编码返回数据=" + poiInfos.size)
                    if (poiInfos.size > 0) {
                        page++
                        if (poiInfos != null || poiInfos.size > 0) {
                            for (obj in poiInfos) {
                                var bean = AddressMapEntity(
                                    obj.name,
                                    obj.address,
                                    obj.location.latitude.toString(),
                                    obj.location.longitude.toString(),
                                    false
                                )
                                dataList.add(bean)
                            }
                        }
                    } else {
                        page = 0
                    }
                    mAdapter.notifyDataSetChanged()

                }
            }
        }
    }


    //POI检索监听器
    var listener: OnGetPoiSearchResultListener = object : OnGetPoiSearchResultListener {
        override fun onGetPoiResult(poiResult: PoiResult) {
            if (poiResult.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {// 没有找到检索结果
                println("###关键词搜索=" + poiResult.error + "=未找到结果")
                ShowToast("未找到结果")
                multiView.showEmpty()
            } else if (poiResult.error == SearchResult.ERRORNO.NO_ERROR) {//检索结果正常返回
//                poiResult.allPoi
                //拿到变化地点后的附近地址
                val poiInfos: MutableList<PoiInfo> = poiResult.allPoi
                println("###获取地理数据=" + poiInfos.size)
                if (poiInfos.size > 0) {
                    page++
                    for (obj in poiInfos) {
                        var bean = AddressMapEntity(
                            obj.name,
                            obj.address,
                            obj.location.latitude.toString(),
                            obj.location.longitude.toString(),
                            false
                        )
                        dataList.add(bean)
                    }
                } else {
                    page = 0
                }

                mAdapter.notifyDataSetChanged()
            }
        }

        override fun onGetPoiDetailResult(poiDetailSearchResult: PoiDetailSearchResult) {}
        override fun onGetPoiIndoorResult(poiIndoorResult: PoiIndoorResult) {}

        //废弃
        override fun onGetPoiDetailResult(poiDetailResult: PoiDetailResult) {}
    }

    //    初始化刷新控件
    private fun initRefreshLayout() {
        smartLayout.setEnableRefresh(false)
        smartLayout.setOnRefreshListener {
//            requestData()
        }
        smartLayout.setOnLoadMoreListener {
            if (searchType == 1) {//1为地理编码 地图点击 2 关键字检索
                initGeoCoder(latLngs)
            }else if (searchType == 2) {
                initSearch()
            }
        }
    }

    private var geocoder: GeoCoder? = null//地理编码
    private var mPoiSearch: PoiSearch? = null//条件检索
    private var marker: Marker? = null
    private lateinit var mAdapter: PMapAdapter
    private var dataList: MutableList<AddressMapEntity> = mutableListOf()
    private var bitmap: BitmapDescriptor? = null

    //初始化列表 PMapAdapter
    private fun initRecyclerView() {
        rv_list.isNestedScrollingEnabled = false
        mAdapter = PMapAdapter(dataList, Box.context)
        rv_list.adapter = mAdapter
        rv_list.layoutManager = LinearLayoutManager(Box.context)
        //创建marker icon
        bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.icon_map_marker)
        mAdapter.setOnTypeClickListener { obj, position, flag ->
            if (flag == ITEM_CLICK) {//
                mBaiduMap?.clear()
                marker?.remove()
//                ShowToast("111")
                // 定义Maker坐标点
                var latLng = LatLng(obj.lat.toDouble(), obj.lon.toDouble())
                //创建marker  在地图上添加Marker
                val ooA = MarkerOptions().position(latLng).icon(bitmap).zIndex(15).draggable(true)
                //添加marker
                marker = mBaiduMap?.addOverlay(ooA) as Marker
                val mapStatusUpdate =
                    MapStatusUpdateFactory.newLatLngZoom(latLng, 18.0f) //18.0f标识缩放等级设置为18级
                mBaiduMap?.animateMapStatus(mapStatusUpdate, 300)
                for (item in dataList) {
                    item.check = item.name == obj.name
                }
                mAdapter.notifyDataSetChanged()
                //点击后返回结果
                var bundle=Bundle()
                bundle.putString("address",obj.address)
                var intent = Intent()
                intent.putExtra("key", bundle)
                setResult(Activity.RESULT_OK, intent)
                finish()
            }
        }
        //模拟数据
        /* if (mAdapter.itemCount == 0) {
             var lists: MutableList<String> = mutableListOf("","")
             dataList.addAll(lists)
             mAdapter.notifyDataSetChanged()
         }*/
    }


    override fun onStop() {
        // 取消注册传感器监听
//        mSensorManager?.unregisterListener(sensorEventListener)
        super.onStop()

    }

    override fun onResume() {
        super.onResume()
        mapView.onResume()
        // 为系统的方向传感器注册监听器
        /*mSensorManager?.registerListener(
            sensorEventListener,
            mSensorManager?.getDefaultSensor(Sensor.TYPE_ORIENTATION),
            SensorManager.SENSOR_DELAY_UI
        )*/
    }

    override fun onDestroy() {
        mPoiSearch?.destroy();
        super.onDestroy()
        mBaiduMap?.isMyLocationEnabled = false

    }

    private var mCurrentDirection = 0
    private var lastX = 0.0

    //传感监听器
    internal var sensorEventListener: SensorEventListener = object : SensorEventListener {
        override fun onSensorChanged(sensorEvent: SensorEvent) {
            //每次方向改变，重新给地图设置定位数据，用上一次onReceiveLocation得到的经纬度、精度
            val x = sensorEvent.values[SensorManager.DATA_X].toDouble()
            if (Math.abs(x - lastX) > 1.0) {// 方向改变大于1度才设置，以免地图上的箭头转动过于频繁
                mCurrentDirection = x.toInt()
                locData = MyLocationData.Builder().accuracy(UserCache.radius)
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(mCurrentDirection.toFloat())
                    .latitude(java.lang.Double.parseDouble(UserCache.lat))
                    .longitude(java.lang.Double.parseDouble(UserCache.lon)).build()
                mBaiduMap?.setMyLocationData(locData)
            }
            lastX = x


        }

        override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {

        }
    }


    override fun closeMvp() {
    }


    private var latLngs:LatLng?=null
    //此方法就是点击地图监听
    override fun onMapClick(latLng: LatLng?) {
        et_address.setTextEx("")
        //设置PoiCitySearchOption，发起检索请求
        //默认使用附近检查
//        mPoiSearch?.searchNearby(PoiNearbySearchOption().location(latLng).radius(1000).keyword("路").pageNum(10))
        latLngs=latLng
        //获取经纬度
        val latitude = latLng!!.latitude
        val longitude = latLng!!.longitude
        println("latitude=$latitude,longitude=$longitude")
        //先清除图层
        mBaiduMap!!.clear()
        // 定义Maker坐标点
        val point = LatLng(latitude, longitude)
        // 构建MarkerOption，用于在地图上添加Marker
        val options = MarkerOptions().position(point)
            .icon(bitmap)
        // 在地图上添加Marker，并显示
        mBaiduMap!!.addOverlay(options)
        //拿到经纬度之后，就可以反地理编码获取地址信息了
        initGeoCoder(latLng)

        /* geocoder?.setOnGetGeoCodeResultListener(object : OnGetGeoCoderResultListener {
             override fun onGetReverseGeoCodeResult(geoCodeResult: ReverseGeoCodeResult) { //获取点击的坐标地址
 //                address = arg0.address
                 System.out.println("address=${geoCodeResult.address}")
                 if (geoCodeResult?.location != null) {
                     if (geoCodeResult.error !== SearchResult.ERRORNO.NO_ERROR) { //没有检索到结果
                         ShowToast("未找到结果")
                         return
                     } else {
                         val latitude: kotlin.Double = geoCodeResult.getLocation().latitude
                         val longitude: kotlin.Double = geoCodeResult.getLocation().longitude
                         //拿到变化地点后的附近地址
                         val poiInfos: MutableList<PoiInfo> = geoCodeResult.poiList
                         println("###获取地理数据=" + poiInfos.size)
                         dataList.clear()
                         for (obj in poiInfos) {
                             var bean = AddressMapEntity(
                                 obj.name,
                                 obj.address,
                                 obj.location.latitude.toString(),
                                 obj.location.longitude.toString(),
                                 false
                             )
                             dataList.add(bean)
                         }
                         mAdapter.notifyDataSetChanged()

                     }
                 }
             }

             override fun onGetGeoCodeResult(arg0: GeoCodeResult) {}
         })*/
    }

    override fun onMapPoiClick(p0: MapPoi?): Boolean {
        return false
    }


}
